/**
 * Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.ruiyin.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import net.sf.json.JSONObject;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.jfinal.MsgController;
import com.jfinal.weixin.sdk.msg.in.InImageMsg;
import com.jfinal.weixin.sdk.msg.in.InLinkMsg;
import com.jfinal.weixin.sdk.msg.in.InLocationMsg;
import com.jfinal.weixin.sdk.msg.in.InShortVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.InVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.jfinal.weixin.sdk.msg.in.event.InCustomEvent;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMassEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InPoiCheckNotifyEvent;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.in.event.InShakearoundUserShakeEvent;
import com.jfinal.weixin.sdk.msg.in.event.InTemplateMsgEvent;
import com.jfinal.weixin.sdk.msg.in.event.InVerifyFailEvent;
import com.jfinal.weixin.sdk.msg.in.event.InVerifySuccessEvent;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutImageMsg;
import com.jfinal.weixin.sdk.msg.out.OutMusicMsg;
import com.jfinal.weixin.sdk.msg.out.OutNewsMsg;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.jfinal.weixin.sdk.msg.out.OutVoiceMsg;
import com.ruiyin.bean.Microchannelinformation;
import com.ruiyin.bean.Microchannelstate;
import com.ruiyin.service.MicrochannelstateService;
import com.ruiyin.util.TemplateApi;

/**
 * 将此 DemoController 在YourJFinalConfig 中注册路由，
 * 并设置好weixin开发者中心的 URL 与 token ，使 URL 指向该
 * DemoController 继承自父类 WeixinController 的index
 * 方法即可直接运行看效果，在此基础之上修改相关的方法即可进行实际项目开发
 */
public class WeixinMsgControlle extends MsgController {
	
	/*private static final String helpStr = "\t发送 help 可获得帮助，发送 \"美女\" 可看美女，发送 news 可看新闻，发送 music 可听音乐，你还可以试试发送图片、语音、位置、收藏等信息，看会有什么 。公众号持续更新中，想要更多惊喜欢迎每天关注 ^_^";
	*/
	private static final String helpStr = "\t 老大,侯爷爷   你们好 ^_^";
	
	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的  ApiConfig 对象即可
	 * 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值
	 */
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));
		
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}
	
	/**
	 * 实现父类抽方法，处理文本消息
	 * 本例子中根据消息中的不同文本内容分别做出了不同的响应，同时也是为了测试 jfinal weixin sdk的基本功能：
	 *     本方法仅测试了 OutTextMsg、OutNewsMsg、OutMusicMsg 三种类型的OutMsg，
	 *     其它类型的消息会在随后的方法中进行测试
	 */
	protected void processInTextMsg(InTextMsg inTextMsg) {
		String msgContent = inTextMsg.getContent().trim();
		String appIDs = PropKit.get("appId");
		String requestUrl= "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appIDs+"&redirect_uri=http://excg82nmgm.proxy.qqbrowser.cc/wxmarket/auth/autha&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		
   	 	String  userInfo = sendGet(requestUrl);
		// 帮助提示
		if ("help".equalsIgnoreCase(msgContent)) {
			OutTextMsg outMsg = new OutTextMsg(inTextMsg);
			outMsg.setContent(helpStr);
			render(outMsg);
		}
		// 图文消息测试
		else if ("news".equalsIgnoreCase(msgContent)) {
			OutNewsMsg outMsg = new OutNewsMsg(inTextMsg);
			outMsg.addNews("JFinal 1.8 发布，JAVA 极速 WEB+ORM 框架", "wweeee ^_^", "http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq1ibBkhSA1BibMuMxLuHIvUfiaGsK7CC4kIzeh178IYSHbYQ5eg9tVxgEcbegAu22Qhwgl5IhZFWWXUw/0", "http://mp.weixin.qq.com/s?__biz=MjM5ODAwOTU3Mg==&mid=200313981&idx=1&sn=3bc5547ba4beae12a3e8762ababc8175#rd");
			outMsg.addNews("JFinal 1.6 发布,JAVA极速WEB+ORM框架", "JFinal 1.6 主要升级了 ActiveRecord 插件，本次升级全面支持多数源、多方言、多缓", "http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq0fcR8VmNCgugHXv7gVlxI6w95RBlKLdKUTjhOZIHGSWsGvjvHqnBnjIWHsicfcXmXlwOWE6sb39kA/0", "http://mp.weixin.qq.com/s?__biz=MjM5ODAwOTU3Mg==&mid=200121522&idx=1&sn=ee24f352e299b2859673b26ffa4a81f6#rd");
			render(outMsg);
		}
		// 音乐消息测试
		else if ("music".equalsIgnoreCase(msgContent)) {
			OutMusicMsg outMsg = new OutMusicMsg(inTextMsg);
			outMsg.setTitle("Listen To Your Heart");
			outMsg.setDescription("建议在 WIFI 环境下流畅欣赏此音乐");
			outMsg.setMusicUrl("http://www.jfinal.com/Listen_To_Your_Heart.mp3");
			outMsg.setHqMusicUrl("http://www.jfinal.com/Listen_To_Your_Heart.mp3");
			outMsg.setFuncFlag(true);
			render(outMsg);
		}
		else if ("美女".equalsIgnoreCase(msgContent)) {
			OutNewsMsg outMsg = new OutNewsMsg(inTextMsg);
			outMsg.addNews("我们只看美女", "又一大波美女来袭，我们只看美女 ^_^", "https://mmbiz.qlogo.cn/mmbiz/zz3Q6WSrzq3DmIGiadDEicRIp69r1iccicwKEUOKuLhYgjibyU96ia581gCf5o3kicqz6ZLdsDyUtLib0q0hdgHtZOf4Wg/0", "http://mp.weixin.qq.com/s?__biz=MjM5ODAwOTU3Mg==&mid=202080887&idx=1&sn=0649c67de565e2d863bf3b8feee24da0#rd");
			// outMsg.addNews("秀色可餐", "JFinal Weixin 极速开发就是这么爽，有木有 ^_^", "http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq2GJLC60ECD7rE7n1cvKWRNFvOyib4KGdic3N5APUWf4ia3LLPxJrtyIYRx93aPNkDtib3ADvdaBXmZJg/0", "http://mp.weixin.qq.com/s?__biz=MjM5ODAwOTU3Mg==&mid=200987822&idx=1&sn=7eb2918275fb0fa7b520768854fb7b80#rd");
			
			render(outMsg);
		}else if ("交易提醒".equalsIgnoreCase(msgContent)) {
			String openid = inTextMsg.getFromUserName();
//			String str = " {\n" +
//			"           \"touser\":\""+openid+"\",\n" +
//			"           \"template_id\":\"2hFPvK-b3x3Yfj9dewd6Qi-t7T4Z1HB0j2cLwb_cAjc\",\n" +
//			"           \"url\":\"http://www.baidu.com\",\n" +
//			"           \"topcolor\":\"#FF0000\",\n" +
//			"           \"data\":{\n" +
//			"                   \"User\": {\n" +
//			"                       \"value\":\"黄先生\",\n" +   
//			"                       \"color\":\"#173177\"\n" +
//			"                   },\n" +
//			"                   \"Date\":{\n" +
//			"                       \"value\":\"06月07日 19时24分\",\n" +
//			"                       \"color\":\"#173177\"\n" +
//			"                   },\n" +
//			"                   \"CardNumber\":{\n" +
//			"                       \"value\":\"042623\",\n" +
//			"                       \"color\":\"#173177\"\n" +
//			"                   },\n" +
//			"                   \"Type\":{\n" +
//			"                       \"value\":\"消费\",\n" +
//			"                       \"color\":\"#173177\"\n" +
//			"                   },\n" +
//			"                   \"Money\":{\n" +
//			"                       \"value\":\"人民币260.00元\",\n" +
//			"                       \"color\":\"#173177\"\n" +
//			"                   },\n" +
//			"                   \"DeadTime\":{\n" +
//			"                       \"value\":\"06月07日19时24分\",\n" +
//			"                       \"color\":\"#173177\"\n" +
//			"                   },\n" +
//			"                   \"Left\":{\n" +
//			"                       \"value\":\"6504.49\",\n" +
//			"                       \"color\":\"#173177\"\n" +
//			"                   }\n" +
//			"           }\n" +
//			"       }";
			String str = " {\n" +
			"           \"touser\":\""+openid+"\",\n" +
			"           \"template_id\":\"JaNUY3PYDAd2yyL9-wzky0JVD7yvuhVCqdW-gEwRypM\",\n" +
			"           \"url\":\"http://www.baidu.com\",\n" +
			"           \"topcolor\":\"#FF0000\",\n" +
			"           \"data\":{\n" +
			"                   \"first\": {\n" +
			"                       \"value\":\"您好，您已排队\",\n" +   
			"                       \"color\":\"#173177\"\n" +
			"                   },\n" +
			"                   \"keyword1\":{\n" +
			"                       \"value\":\"A011\",\n" +
			"                       \"color\":\"#173177\"\n" +
			"                   },\n" +
			"                   \"keyword2\":{\n" +
			"                       \"value\":\"2016-8-29\",\n" +
			"                       \"color\":\"#173177\"\n" +
			"                   },\n" +
			"                   \"keyword3\":{\n" +
			"                       \"value\":\"545566666**234\",\n" +
			"                       \"color\":\"#173177\"\n" +
			"                   },\n" +
			"                   \"keyword4\":{\n" +
			"                       \"value\":\"南昌市中山路159号总行营业部\",\n" +
			"                       \"color\":\"#173177\"\n" +
			"                   },\n" +
			"                   \"keyword5\":{\n" +
			"                       \"value\":\"0791-86790777\",\n" +
			"                       \"color\":\"#173177\"\n" +
			"                   },\n" +
			"                   \"remark\":{\n" +
			"                       \"value\":\"备注：请您提前至营业网点刷卡取号，以免失效！\",\n" +
			"                       \"color\":\"#173177\"\n" +
			"                   }\n" +
			"           }\n" +
			"       }";
			ApiResult ar = TemplateMsgApi.send(str);
	//render(apiResult.getJson());
	OutTextMsg outMsg = new OutTextMsg(inTextMsg);
	outMsg.setContent("微信查询，方便快捷！");
	render(outMsg);
		}
		// 其它文本消息直接返回原值 + 帮助提示
		else {
			OutTextMsg outMsg = new OutTextMsg(inTextMsg);
			outMsg.setContent("\t文本消息已成功接收，内容为： " + inTextMsg.getContent() + "\n\n" + helpStr);
			render(outMsg);
		}
	}
	
	/**
	 * 实现父类抽方法，处理图片消息
	 */
	protected void processInImageMsg(InImageMsg inImageMsg) {
		OutImageMsg outMsg = new OutImageMsg(inImageMsg);
		// 将刚发过来的图片再发回去
		outMsg.setMediaId(inImageMsg.getMediaId());
		render(outMsg);
	}
	
	/**
	 * 实现父类抽方法，处理语音消息
	 */
	protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
		OutVoiceMsg outMsg = new OutVoiceMsg(inVoiceMsg);
		// 将刚发过来的语音再发回去
		outMsg.setMediaId(inVoiceMsg.getMediaId());
		render(outMsg);
	}
	
	/**
	 * 实现父类抽方法，处理视频消息
	 */
	protected void processInVideoMsg(InVideoMsg inVideoMsg) {
		/* 腾讯 api 有 bug，无法回复视频消息，暂时回复文本消息代码测试
		OutVideoMsg outMsg = new OutVideoMsg(inVideoMsg);
		outMsg.setTitle("OutVideoMsg 发送");
		outMsg.setDescription("刚刚发来的视频再发回去");
		// 将刚发过来的视频再发回去，经测试证明是腾讯官方的 api 有 bug，待 api bug 却除后再试
		outMsg.setMediaId(inVideoMsg.getMediaId());
		render(outMsg);
		*/
		OutTextMsg outMsg = new OutTextMsg(inVideoMsg);
		outMsg.setContent("\t视频消息已成功接收，该视频的 mediaId 为: " + inVideoMsg.getMediaId());
		render(outMsg);
	}
	
	/**
	 * 实现父类抽方法，处理地址位置消息
	 */
	protected void processInLocationMsg(InLocationMsg inLocationMsg) {
		OutTextMsg outMsg = new OutTextMsg(inLocationMsg);
		outMsg.setContent("已收到地理位置消息:" +
							"\nlocation_X = " + inLocationMsg.getLocation_X() +
							"\nlocation_Y = " + inLocationMsg.getLocation_Y() + 
							"\nscale = " + inLocationMsg.getScale() +
							"\nlabel = " + inLocationMsg.getLabel());
		render(outMsg);
	}
	
	/**
	 * 实现父类抽方法，处理链接消息
	 * 特别注意：测试时需要发送我的收藏中的曾经收藏过的图文消息，直接发送链接地址会当做文本消息来发送
	 */
	protected void processInLinkMsg(InLinkMsg inLinkMsg) {
		OutNewsMsg outMsg = new OutNewsMsg(inLinkMsg);
		outMsg.addNews("链接消息已成功接收", "链接使用图文消息的方式发回给你，还可以使用文本方式发回。点击图文消息可跳转到链接地址页面，是不是很好玩 :)" , "http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq1ibBkhSA1BibMuMxLuHIvUfiaGsK7CC4kIzeh178IYSHbYQ5eg9tVxgEcbegAu22Qhwgl5IhZFWWXUw/0", inLinkMsg.getUrl());
		render(outMsg);
	}
	
	/**
	 * 实现父类抽方法，处理关注/取消关注消息
	 */
	protected void processInFollowEvent(InFollowEvent inFollowEvent) {
		try {
			OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
			String openid = inFollowEvent.getFromUserName();
		
			//outMsg.setContent("感谢关注 JFinal Weixin 极速开发，为您节约更多时间，去陪恋人、家人和朋友 :) \n\n\n " + helpStr);
			// 如果为取消关注事件，将无法接收到传回的信息
			if (InFollowEvent.EVENT_INFOLLOW_SUBSCRIBE.equals(inFollowEvent.getEvent()))
			{
				// 配置微信 API 相关常量
				String appIDs = PropKit.get("appId");
				String appSecrets = PropKit.get("appSecret");
				String requestUrl= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appIDs+"&secret="+appSecrets;
				
				JSONObject jsonObject = httpRequst(requestUrl, "GET", null);
				String urls="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+URLDecoder.decode(jsonObject.get("access_token").toString(),"UTF-8")+"&openid="+openid+"&lang=zh_CN";
				JSONObject userInfo = httpRequst(urls, "GET", null);
				Microchannelinformation microchannelinformation = getModel(Microchannelinformation.class);
				microchannelinformation.setCity(userInfo.get("city").toString());
				microchannelinformation.setCountry(userInfo.get("country").toString());
				microchannelinformation.setHeadimgurl(userInfo.get("headimgurl").toString());
				microchannelinformation.setNickname(userInfo.get("nickname").toString());
				microchannelinformation.setOpenid(userInfo.get("openid").toString());
				microchannelinformation.setSex(userInfo.get("sex").toString());
				microchannelinformation.save();
				
				Microchannelstate microchannelstate = getModel(Microchannelstate.class);
				microchannelstate.setOpenid(userInfo.get("openid").toString());
				microchannelstate.setState("add");
				microchannelstate.setHeadimgurl(userInfo.get("headimgurl").toString());
				microchannelstate.save();
				
				try {
					outMsg.setContent("您好，jsruiyin感谢您的关注！");
					render(outMsg);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// 如果为取消关注事件，将无法接收到传回的信息
			if (InFollowEvent.EVENT_INFOLLOW_UNSUBSCRIBE.equals(inFollowEvent.getEvent()))
			{
				Microchannelinformation microchannelinformation = getModel(Microchannelinformation.class);
				microchannelinformation.setOpenid(openid);
				microchannelinformation.delete();
				
				MicrochannelstateService microchannelstateService =new MicrochannelstateService();
				List<Microchannelstate> list =microchannelstateService.paginates(openid);
				if(list.size()>0){
					microchannelstateService.delete(openid);
				}else{
					//取消关注的用户前台暂时不需要处理
//				Microchannelstate microchannelstate = getModel(Microchannelstate.class);
//				microchannelstate.setOpenid(openid);
//				microchannelstate.setState("delete");
//				microchannelstate.save();
				}
				//render(outMsg);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 实现父类抽方法，处理扫描带参数二维码事件
	 */
	protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
		OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
		String openid = inQrCodeEvent.getFromUserName();
		String str = " {\n" +
		"           \"touser\":\""+openid+"\",\n" +
		"           \"template_id\":\"JaNUY3PYDAd2yyL9-wzky0JVD7yvuhVCqdW-gEwRypM\",\n" +
		"           \"url\":\"http://www.baidu.com\",\n" +
		"           \"topcolor\":\"#FF0000\",\n" +
		"           \"data\":{\n" +
		"                   \"first\": {\n" +
		"                       \"value\":\"您好，您已排队\",\n" +   
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"keyword1\":{\n" +
		"                       \"value\":\"A011\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"keyword2\":{\n" +
		"                       \"value\":\"2016-8-29\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"keyword3\":{\n" +
		"                       \"value\":\"545566666**234\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"keyword4\":{\n" +
		"                       \"value\":\"南昌市中山路159号总行营业部\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"keyword5\":{\n" +
		"                       \"value\":\"0791-86790777\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   },\n" +
		"                   \"remark\":{\n" +
		"                       \"value\":\"备注：请您提前至营业网点刷卡取号，以免失效！\",\n" +
		"                       \"color\":\"#173177\"\n" +
		"                   }\n" +
		"           }\n" +
		"       }";
		ApiResult ar = TemplateMsgApi.send(str);
		TemplateApi TemplateApi = new TemplateApi();
		TemplateApi.send(str);
		outMsg.setContent("processInQrCodeEvent() 方法测试成功");
		render(outMsg);
	}
	
	/**
	 * 实现父类抽方法，处理上报地理位置事件
	 */
	protected void processInLocationEvent(InLocationEvent inLocationEvent) {
		OutTextMsg outMsg = new OutTextMsg(inLocationEvent);
		outMsg.setContent("processInLocationEvent() 方法测试成功");
		render(outMsg);
	}
	
	/**
	 * 实现父类抽方法，处理自定义菜单事件
	 */
	protected void processInMenuEvent(InMenuEvent inMenuEvent) {
		String openid = inMenuEvent.getFromUserName();
		String urls = "http://smartbank.jsruiyin.com/hbprefillsystem/index.jsp?openid="+openid;
		OutNewsMsg outMsg = new OutNewsMsg(inMenuEvent);
		outMsg.addNews("湖北邮政微信预约", "微信预约叫号，微信预填单 ^_^", "http://smartbank.jsruiyin.com/guard/uploadFiles/1.jpg", urls);
		//renderOutTextMsg("processInMenuEvent() 方法测试成功");
		render(outMsg);
	}
	
	/**
	 * 实现父类抽方法，处理接收语音识别结果
	 */
	protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults) {
		renderOutTextMsg("语音识别结果： " + inSpeechRecognitionResults.getRecognition());
	}

	@Override
	protected void processInCustomEvent(InCustomEvent inCustomEvent) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void processInMassEvent(InMassEvent inMassEvent) {
		// TODO Auto-generated method stub
		
	}

	
	@Override
	protected void processInPoiCheckNotifyEvent(
			InPoiCheckNotifyEvent inPoiCheckNotifyEvent) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void processInShakearoundUserShakeEvent(
			InShakearoundUserShakeEvent inShakearoundUserShakeEvent) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void processInShortVideoMsg(InShortVideoMsg inShortVideoMsg) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void processInTemplateMsgEvent(
			InTemplateMsgEvent inTemplateMsgEvent) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void processInVerifyFailEvent(InVerifyFailEvent inVerifyFailEvent) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void processInVerifySuccessEvent(
			InVerifySuccessEvent inVerifySuccessEvent) {
		// TODO Auto-generated method stub
		
	}
	
	
	 public JSONObject httpRequst(String requestUrl,String requetMethod,String outputStr){
			JSONObject jsonobject=null;
			StringBuffer buffer=new StringBuffer();
			try
			{
				//创建SSLContext对象，并使用我们指定的新人管理器初始化
				TrustManager[] tm={new MyX509TrustManager()};
				SSLContext sslcontext=SSLContext.getInstance("SSL","SunJSSE");
				sslcontext.init(null, tm, new java.security.SecureRandom());
				//从上述SSLContext对象中得到SSLSocktFactory对象
				SSLSocketFactory ssf=sslcontext.getSocketFactory();
				
				URL url=new URL(requestUrl);
				HttpsURLConnection httpUrlConn=(HttpsURLConnection)url.openConnection();
				httpUrlConn.setSSLSocketFactory(ssf);
				
				httpUrlConn.setDoOutput(true);
				httpUrlConn.setDoInput(true);
				httpUrlConn.setUseCaches(false);
				//设置请求方式（GET/POST）
				httpUrlConn.setRequestMethod(requetMethod);
				
				if("GET".equalsIgnoreCase(requetMethod))
					httpUrlConn.connect();
				
				//当有数据需要提交时
				if(null!=outputStr)
				{
				OutputStream outputStream=httpUrlConn.getOutputStream();
				//注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
				}
				
				//将返回的输入流转换成字符串
				InputStream inputStream=httpUrlConn.getInputStream();
				InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8");
				BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
				
				
				String str=null;
				while((str = bufferedReader.readLine()) !=null)
				{ 
					buffer.append(str);
				}
				bufferedReader.close();
				inputStreamReader.close();
				//释放资源
				inputStream.close();
				inputStream=null;
				httpUrlConn.disconnect();
				jsonobject=JSONObject.fromObject(buffer.toString());
			}
			catch (ConnectException ce) {
				// TODO: handle exception
				ce.printStackTrace();
			}
			catch (Exception e) { 
				e.printStackTrace();
			}
			return jsonobject;
		}
	 
	 
	 public String sendGet(String urlNameString) {
	        String result = "";
	        BufferedReader in = null;
	        try {
	            
	            URL realUrl = new URL(urlNameString);
	            // 打开和URL之间的连接
	            URLConnection connection = realUrl.openConnection();
	            // 设置通用的请求属性
	            connection.setRequestProperty("accept", "*/*");
	            connection.setRequestProperty("connection", "Keep-Alive");
	            connection.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            // 建立实际的连接
	            connection.connect();
	            // 获取所有响应头字段
	            Map<String, List<String>> map = connection.getHeaderFields();
	            // 遍历所有的响应头字段
	            for (String key : map.keySet()) {
	                System.out.println(key + "--->" + map.get(key));
	            }
	            // 定义 BufferedReader输入流来读取URL的响应
	            in = new BufferedReader(new InputStreamReader(
	                    connection.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	        } catch (Exception e) {
	            System.out.println("发送GET请求出现异常！" + e);
	            e.printStackTrace();
	        }
	        // 使用finally块来关闭输入流
	        finally {
	            try {
	                if (in != null) {
	                    in.close();
	                }
	            } catch (Exception e2) {
	                e2.printStackTrace();
	            }
	        }
	        return result;
	    }
}
